#!/bin/bash

cd ${0%/*}

read VERSION < version

NAME=netid
PRODUCT_NAME="Net iD"

echo
echo "$PRODUCT_NAME $VERSION"
echo "Copyright Pointsharp AB"
echo

USER_VALUE=$(id -a)
USER_ENTRY=${USER_VALUE%%(*}
USER_UID=${USER_ENTRY##*=}
USER_NAME=$(logname)
if [ -z "$USER_NAME" ]; then
    USER_NAME=${HOME##*/}
fi

if [ "$USER_UID" != "0" ]; then
    echo "ACCESS DENIED: Uninstallation require root privilege"
    echo
    exit 0
fi

if [ $(uname) = "Darwin" ]; then 
    LIBEXT="dylib"
    LIB_DIR=/usr/local/lib
    BIN_DIR=/usr/local/bin
else  
    HOME=/home/$USER_NAME
    LIBEXT="so"
    LIB_DIR=/usr/lib
    BIN_DIR=/usr/bin
fi

APP_NAME="$NAME"app
APP_NAME2=$PRODUCT_NAME.app
CMD_NAME=$NAME
LIB_NAME=lib$NAME.$LIBEXT
GUI_NAME=lib"$NAME"gui.$LIBEXT
CFG_NAME=$NAME.conf
CTX_NAME=lib"$NAME"ctx.$LIBEXT

APP_DIR=$LIB_DIR/$NAME
APP_DIR2=/Applications
CFG_DIR=/etc
RES_DIR=$APP_DIR
CTX_DIR=/opt/Citrix/ICAClient

echo "Unstallation started"
if [ -d "$CTX_DIR" ]; then
    if [ -f $BIN_DIR/$NAME ]; then
        echo "Configure Citrix Workspace App"
        chmod 644 "$CTX_DIR/config/AuthManConfig.xml"
        chmod 644 "$CTX_DIR/config/module.ini"
        $BIN_DIR/$CMD_NAME -setup vd -uninstall -path "$CTX_DIR" -file "$CTX_NAME"
        chmod 444 "$CTX_DIR/config/AuthManConfig.xml"
        chmod 444 "$CTX_DIR/config/module.ini"
    fi
fi
echo "Stop services"
if [ -f "$HOME/Library/LaunchAgents/com.pointsharp.$NAME.monitor.plist" ]; then
    if [ -f $BIN_DIR/$NAME ]; then
        $BIN_DIR/$NAME -service stop
    fi
fi
NAME_MONITOR="$NAME"_monitor.desktop
if [ -f "$HOME/.config/autostart/$NAME_MONITOR" ]; then
    if [ -f $BIN_DIR/$NAME ]; then
        $BIN_DIR/$NAME -service stop
    fi
fi
echo "Unregister components"
if [ -f "$PWD/uninstall_webext.sh" ]; then
    "$PWD/uninstall_webext.sh"
fi
echo "Remove components"
if [ -L "/Library/$PRODUCT_NAME" ]; then
    rm -f "/Library/$PRODUCT_NAME"
fi
if [ -d "$APP_DIR" ]; then
    rm -rf "$APP_DIR"
fi
if [ -d "$APP_DIR2/$APP_NAME2" ]; then
    rm -rf "$APP_DIR2/$APP_NAME2"
fi
if [ -L "$BIN_DIR/$APP_NAME" ]; then
    rm -f "$BIN_DIR/$APP_NAME"
fi
if [ -L "$BIN_DIR/$CMD_NAME" ]; then
    rm -f "$BIN_DIR/$CMD_NAME"
fi
if [ -L "$LIB_DIR/$LIB_NAME" ]; then
    rm -f "$LIB_DIR/$LIB_NAME"
fi
if [ -f "$CFG_DIR/$CFG_NAME" ]; then
    rm -f "$CFG_DIR/$CFG_NAME"
fi
if [ -d "$RES_DIR" ]; then
    rm -rf "$RES_DIR"
fi
if [ -f "/usr/share/applications/$NAME.desktop" ]; then
    rm -f "/usr/share/applications/$NAME.desktop"
fi
if [ -f "$HOME/Library/LaunchAgents/com.pointsharp.$NAME.monitor.plist" ]; then
    rm -f "$HOME/Library/LaunchAgents/com.pointsharp.$NAME.monitor.plist"
fi
if [ -f "$HOME/.config/autostart/$NAME_MONITOR" ]; then
    rm -f "$HOME/.config/autostart/$NAME_MONITOR"
fi
echo "Remove temporary files"
rm -f /tmp/~$NAME*

echo "Uninstallation successful"
